package mytest;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

@WebServlet("/addContact")
public class AddContactServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String name = request.getParameter("name");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact", "root", "root123");

            PreparedStatement ps = conn.prepareStatement("INSERT INTO contacts (name, address, phone) VALUES (?, ?, ?)");
            ps.setString(1, name);
            ps.setString(2, address);
            ps.setString(3, phone);
            ps.executeUpdate();
            // 重定向到联系人列表页面
            response.sendRedirect("/contact");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

